package org.lab.mtga.core.services.impl;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Singleton;

import net.sf.flatpack.DataSet;
import net.sf.flatpack.DefaultParserFactory;
import net.sf.flatpack.Parser;

import org.lab.mtga.core.exception.CardNotFound;
import org.lab.mtga.core.model.Card;
import org.lab.mtga.core.services.CardRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class CsvCardRepository implements CardRepository {

	private static final Logger LOG = LoggerFactory.getLogger(CsvCardRepository.class);

	private List<Card> cards;

	public void init(InputStream inputStream) {
		try {
			Reader reader = new InputStreamReader(inputStream, "UTF8");
			Parser parser = DefaultParserFactory.getInstance().newDelimitedParser(reader, ',', '"');
			DataSet dataSet = parser.parse();
			cards = new ArrayList<Card>();
			while (dataSet.next()) {
				Card card = new Card();
				card.setName(dataSet.getString("NAME"));
				// card.setType(dataSet.getInt("TYPE"));
				cards.add(card);
				LOG.debug("Added local card '{}'", card.getName());
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	@Override
	public Card findByName(String name) {
		for (Card card : cards) {
			if (name.equalsIgnoreCase(card.getName())) {
				return card;
			}
		}
		throw new CardNotFound(name);
	}
}
